<template>
  <div class="register-container">
    <el-card class="register-card">
      <h2>用户注册</h2>
      <el-form :model="registerForm" :rules="rules" ref="registerFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="registerForm.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="registerForm.password" type="password" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="registerForm.confirmPassword" type="password" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="registerForm.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registerForm.email" />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleAvatarChange"
            accept="image/*"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleRegister" :loading="loading" class="register-button">注册</el-button>
          <el-button @click="goToLogin" class="login-button">返回登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useUserStore } from '../stores/user'
import { useRouter } from 'vue-router'
import type { FormInstance, UploadFile } from 'element-plus'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import axios from '../utils/axios'

const userStore = useUserStore()
const router = useRouter()
const loading = ref(false)
const registerFormRef = ref<FormInstance>()
const imageUrl = ref('')
const avatarFile = ref<File | null>(null)

const registerForm = ref({
  username: '',
  password: '',
  confirmPassword: '',
  phone: '',
  email: '',
  avatar: ''
})

// 异步验证用户名是否存在
const validateUsername = async (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入用户名'))
    return
  }
  try {
    const response = await axios.get(`/user/check/username/${value}`)
    if (response.data.data) {
      callback(new Error('用户名已存在'))
    } else {
      callback()
    }
  } catch (error) {
    callback()
  }
}

// 异步验证手机号是否存在
const validatePhone = async (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入手机号'))
    return
  }
  if (!/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error('请输入正确的手机号'))
    return
  }
  try {
    const response = await axios.get(`/user/check/phone/${value}`)
    if (response.data.data) {
      callback(new Error('手机号已被注册'))
    } else {
      callback()
    }
  } catch (error) {
    callback()
  }
}

// 异步验证邮箱是否存在
const validateEmail = async (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入邮箱'))
    return
  }
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
    callback(new Error('请输入正确的邮箱地址'))
    return
  }
  try {
    const response = await axios.get(`/user/check/email/${value}`)
    if (response.data.data) {
      callback(new Error('邮箱已被注册'))
    } else {
      callback()
    }
  } catch (error) {
    callback()
  }
}

const validatePass2 = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.value.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const validatePassword = (rule: any, value: string, callback: any) => {
  const pattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/
  if (!pattern.test(value)) {
    callback(new Error('密码必须包含大小写字母和数字'))
  } else {
    callback()
  }
}

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 20, message: '用户名长度必须在4-20位之间', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, max: 32, message: '密码长度必须在8-32位之间', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validatePass2, trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  avatar: [
    { required: true, message: '请上传头像', trigger: 'change' }
  ]
}

const handleAvatarChange = async (file: UploadFile) => {
  if (!file.raw) return
  const isImage = file.raw.type.startsWith('image/')
  const isLt2M = file.raw.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return
  }

  avatarFile.value = file.raw
  imageUrl.value = URL.createObjectURL(file.raw)
  registerForm.value.avatar = imageUrl.value
}

const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  await registerFormRef.value.validate(async (valid) => {
    if (valid) {
      if (!avatarFile.value) {
        ElMessage.error('请上传头像')
        return
      }

      loading.value = true
      try {
        const formData = new FormData()
        formData.append('avatar', avatarFile.value)
        const { confirmPassword, avatar, ...registerData } = registerForm.value
        formData.append('userRegisterDTO', new Blob([JSON.stringify(registerData)], {
          type: 'application/json'
        }))
        
        const success = await userStore.register(formData)
        if (success) {
          ElMessage.success('注册成功')
          router.push('/login')
        }
      } finally {
        loading.value = false
      }
    }
  })
}

const goToLogin = () => {
  router.push('/login')
}
</script>

<style scoped>
.register-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
}

.register-card {
  width: 500px;
  padding: 20px;
}

.register-card h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #409EFF;
}

.register-button {
  width: 45%;
  margin-right: 10%;
}

.login-button {
  width: 45%;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style> 